package com.server.service.impl;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.server.date.DateType;
import com.server.date.DateUtil;
import com.server.service.ICommonDataService;
import com.server.service.IMsgInforService;
import com.server.web.DataVector;
import com.server.web.RequestInput;

@Service("MsgInforService")
public class MsgInforService implements IMsgInforService {
	
	private final String msgTable = "education.message";

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private ICommonDataService commonDataService;
	
	 /**
	 * 获取消息条数/未读消息条数
	 * @param uuid
	 * @param notRead
	 * @return
	 * @author ServerZhang
	 * @date 2016年9月1日
	 */
	@Override
	public Integer getCount(String uuid,Boolean notRead){
		String sql = "select count(id) from %s where recipient='%s' and state=1 %s";
		return jdbcTemplate.queryForObject(String.format(sql, msgTable,uuid,notRead!=null&&notRead ? "and isRead=0" : ""), Integer.class);
	}
	
	 /**
	 * 获取消息列表
	 * @param uuid
	 * @param notRead
	 * @param requestInput
	 * @return
	 * @author ServerZhang
	 * @date 2016年9月1日
	 */
	@Override
	public DataVector<Map<String, Object>> getList(String uuid,Boolean notRead,RequestInput requestInput){
		String _whereStr = "recipient='"+uuid+"' and state=1";
		_whereStr += notRead!=null&&notRead ? " and isRead=0" : "";
		String sortStr = "factPushTime desc";
		return commonDataService.getListData(msgTable, _whereStr, sortStr, requestInput);
	}
	 /**
	 * 删除
	 * @param id
	 * @return
	 * @author ServerZhang
	 * @date 2016年9月1日
	 */
	@Override
	public Integer delete(String ids){
		String idStr = "'"+ids.replaceAll(",", "','")+"'";
		String sql = "delete from %s where id in(%s)";
		return jdbcTemplate.update(String.format(sql, msgTable,idStr));
	}
	@Override
	public Integer deleteAll(String uuid,Boolean notRead){
		String sql = "delete from %s where recipient='%s' and state=1 %s";
		return jdbcTemplate.update(String.format(sql, msgTable,uuid,notRead!=null&&notRead ? "and isRead=0" : ""));
	}
	 /**
	 * 消息已读
	 * @param ids
	 * @return
	 * @author ServerZhang
	 * @date 2016年9月1日
	 */
	@Override
	public Integer read(String ids){
		String idStr = "'"+ids.replaceAll(",", "','")+"'";
		String sql = "update %s set isRead=1,readTime='%s' where id in(%s)";
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		return jdbcTemplate.update(String.format(sql, msgTable,dateStr,idStr));
	}
}
